package bgw

import (
	"context"
	"fmt"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/emun"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bgw"
	"github.com/spf13/cast"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &bgwSrv{
		MerchantId: config.MerchantId,
		NotifyUrl:  config.NotifyUrl,
		ReturnUrl:  config.ReturnUrl,
		PrivateKey: config.PrivateKey,
		Url:        config.Url,
		AppId:      config.AppId,
		secret:     config.SecretKey,
		appCode:    config.AppCode,
	}
}

type bgwSrv struct {
	MerchantId string
	NotifyUrl  string
	ReturnUrl  string
	PrivateKey string
	Url        string
	AppId      string
	secret     string
	appCode    string
}

func (s *bgwSrv) Withdraw(ctx context.Context, req map[string]any) (resp base.WithdrawRes, err error) {
	order := cast.ToStringMap(req["Order"])
	orderNo := cast.ToString(order["OrderNo"])
	userId := cast.ToString(order["UserId"])
	amount := cast.ToInt64(order["RealAmount"])
	userUsdtWallets := cast.ToStringMap(order["UserUsdtWallets"])
	address := cast.ToString(userUsdtWallets["Address"])
	usdtType := emun.GetUserUsdtWalletNameByType(cast.ToInt(userUsdtWallets["UsdtType"]))
	service := bgw.NewWithdrawService(s.MerchantId, s.AppId, s.appCode, s.secret)
	service.SetUrl(s.Url)
	currencyId := service.GetCurrencyId(usdtType)
	if currencyId == 0 {
		currencyId = 1004
	}
	_param := bgw.WithdrawRequest{
		OuterNo:     orderNo,
		UserId:      userId,
		Currency:    currencyId,
		Amount:      amount,
		Scale:       2,
		Address:     address,
		NotifyURL:   s.NotifyUrl,
		Extend:      "extend",
		Subject:     "subject",
		Description: "description",
		Nickname:    fmt.Sprintf("user_%s", userId),
		Avatar:      "avatar",
	}
	res, err := service.Withdraw(_param)
	if err != nil {
		return
	}
	resp = base.WithdrawRes{
		OrderSn:      res.OuterNo,
		ThirdOrderSn: res.OrderNo,
	}
	return
}
